﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using Microsoft.VisualBasic;
using System.ServiceProcess;

namespace RegisterMachine
{
    class Program
    {
        static void Main(string[] args)
        {
            SetServer();
            Console.WriteLine("Registering machine...");
            RegisterMachine();
            Console.WriteLine("Starting service...");
            StartService();
        }

        private static void StartService()
        {
            ServiceController service = new ServiceController("Mynte");
            try
            {
                service.Start();
            }
            catch
            {
            }
        }

        private static string SetServer()
        {
            Environment.CurrentDirectory = Utilities.Utilities.GetInstallationFolder();
            string ServerURL = string.Empty;
            while (String.IsNullOrEmpty(ServerURL))
                ServerURL = Microsoft.VisualBasic.Interaction.InputBox("Inserire indirizzo server repository:");

            string file = System.IO.File.ReadAllText("WMISrvc.exe.config");
            file = file.Replace("$ServerAddress$", ServerURL);
            System.IO.File.WriteAllText("WMISrvc.exe.config", file);

            file = System.IO.File.ReadAllText(@".\InstallationOperation\InstallationOperation.exe.config");
            file = file.Replace("$ServerAddress$", ServerURL);
            System.IO.File.WriteAllText(@".\InstallationOperation\InstallationOperation.exe.config", file);

            return ServerURL;
        }

        private static void RegisterMachine()
        {
            String commandText = String.Format(@"IF ( SELECT Count(*) 
	                                                  FROM dbo.InstalledMachine 
	                                                  WHERE MachineName='{0}'
	                                                ) < 1
                                                    BEGIN
	                                                  INSERT INTO dbo.InstalledMachine VALUES ('{0}','{1}')
                                                    END", Environment.MachineName, DateTime.Today.ToShortDateString());
            try
            {
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString);
                SqlCommand comm = new SqlCommand(commandText, conn);

                using (conn)
                {
                    conn.Open();
                    using (comm)
                    {
                        comm.ExecuteNonQuery();
                    }
                }

            }
            catch (Exception ex)
            { }
        }

    }
}
